package org.devocean.groupbuying.service.impl;

import java.io.Serializable;
import java.util.List;

import org.devocean.groupbuying.domain.Cart;
import org.devocean.groupbuying.domain.CartItem;
import org.devocean.groupbuying.domain.Discount;
import org.devocean.groupbuying.service.ArticlesService;
import org.devocean.groupbuying.service.CartService;
import org.devocean.groupbuying.service.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CartServiceImpl implements CartService, Serializable {

	private Cart cart;

	@Autowired
	private DiscountService discountService;

	@Autowired
	private ArticlesService articlesService;

	public CartServiceImpl() {
		this.cart = new Cart();
	}

	@Transactional
	public Cart getCurrentCart() {
		return this.cart;
	}

	@Transactional
	public Cart addToCart(Integer discountID, Integer customerID,
			String language) {
		Discount discount = discountService.getDiscountById(discountID);
		List<CartItem> items = cart.getCartItems();
		Boolean flag = true;

		for (CartItem cartItem : items) {
			if (cartItem.getDiscountID().equals(discount.getDiscountID())) {
				cartItem.setQuantity(cartItem.getQuantity() + 1);
				cartItem.setUnitPrice(discount.getDiscountPrice());
				cartItem.setAmount(cartItem.getQuantity()
						* discount.getDiscountPrice());
				cart.setAmount(cart.getAmount() + discount.getDiscountPrice());
				flag = false;
			}
		}

		if (flag) {
			CartItem item = new CartItem(discountID, articlesService
					.getArticleBylang(
							discount.getFormula().getPlan()
									.getArticlesLocalization()
									.getArticlesLocalizationID(), language)
					.getTitle(), 1, discount.getDiscountPrice(),
					discount.getDiscountPrice());

			cart.getCartItems().add(item);
			cart.setAmount(cart.getAmount() + item.getAmount());
		}

		return this.cart;

	}

	@Transactional
	public Cart addToCart(Integer discountID, Integer quantity,
			Integer customerID, String language) {
		Discount discount = discountService.getDiscountById(discountID);

		CartItem item = new CartItem(discountID, articlesService
				.getArticleBylang(
						discount.getFormula().getPlan()
								.getArticlesLocalization()
								.getArticlesLocalizationID(), language)
				.getTitle(), quantity, discount.getDiscountPrice(),
				discount.getDiscountPrice() * quantity);
		cart.setAmount(cart.getAmount() + item.getAmount());
		cart.getCartItems().add(item);

		return this.cart;

	}

	@Transactional
	public void cleanCart() {
		this.cart = new Cart();
	}

}
